<?php
namespace app\repair\controller;
use think\Request;
use app\common\controller\Common;
use think\Exception;
use think\Db;
class Stock extends Common
{
	private $state = 0;//返库状态
	protected $keyword_search = ['sr.goods_name','sr.repair_sn','sr.unit','sr.number','sr.selling_price','sr.trade_price','sr.buying_price'];
	protected $afterActionList = [
        'addOperLog'  =>  ['only'=>'return_house'],
    ];

	public function _initialize()
	{
		parent::_initialize();
        $this->model = model('Stock');
	}

	/**
	 * 维修配件返库列表
	 */
	public function index()
	{
		if(Request()->isGet()){
			if(Request()->isAjax()){
				$this->state = 0;
				$data = input('get.');
				$data = Request()->param('');
				$result = $this->getList($data);
				return $result;
			}
			$Goods = model('Goods');
			$this->assign('cate',$Goods->getRepairCat());
			return $this->fetch('');
		}
	}
	/**
	 * 确认返库,并添加配件库存
	 */
	public function return_house()
	{
		if(Request()->isAjax()){
			$data = Request()->param('');
			try{
				Db::startTrans();
				/*返库状态*/
				$row->state = 1;
				$this->log_id = implode(',', $data['ids']);
				$info = [];
				foreach($data['ids'] as $v){
					$info[] = [
						'stock_repair_id'	=> $v,
						'state'				=> 1,
					];
				}
				$this->model->saveAll($info);
				/*恢复库存*/
				foreach($data['stock_id'] as $k => $v){
					$this->model->incGoodsNumber($v, $data['number'][$k]);
				}
				Db::commit();
				$this->success(config('status.SUCCESS_ONE'));
			}catch(Exception $e){
				Db::rollback();
				$this->error(config('status.ERROR_FIVE').$e->getMessage());
			}
		}
	}
	/**
	 * 返库历史
	 */
	public function log_list()
	{
		if(Request()->isGet()){
			if(Request()->isAjax()){
				$this->state = 1;
				$data = input('get.');
				$data = Request()->param('');
				$result = $this->getList($data);
				return $result;
			}
			$Goods = model('Goods');
			$this->assign('cate',$Goods->getRepairCat());
			return $this->fetch('');
		}
	}
	/**
	 * 获取品牌、内存、属性、颜色数据
	 */
	public function get_attribute()
	{
		if(Request()->isAjax()){
			$data = Request()->param('');
			$info['brand_name'] = $this->model->get_attribute($data['fid'], 0);
			$info['memory_name'] = $this->model->get_attribute($data['fid'], 1);
			$info['attribute_name'] = $this->model->get_attribute($data['fid'], 2);
			$info['colour_name'] = $this->model->get_attribute($data['fid'], 3);
			$this->success(config('status.SUCCESS_ONE'),null,$info);
		}
	}

	/**
	 * 列表数据处理
	 * @param array $data 数据参数
	 */
	protected function handleList($data)
	{
		$where['sr.state'] = $this->state;
		$where['g.category_id'] = config('parameter.repair_cat_id');
		/*@商品查询字段*/
		$goods = ['attribute_name','brand_name','cat_id','colour_name','memory_name'];
		foreach($goods as $v){
			if(isset($data[$v]) && $data[$v] != ''){
				$where['g.'.$v] = $data[$v];
			}
		}
		/*返库时间*/
		if($this->cusTime($data)){
			$where['sr.ret_time'] = $this->cusTime($data);
		}
		return $where;
	}
}